import {createRouter, createWebHistory} from "vue-router";
import {decodeJwt, getJwt} from "@/api/jwt.js";

const routes = [
    {
        name: "login",
        path: "/login",
        component: () => import("@/components/views/Login.vue")
    },
    {
        name: "adminMain",
        path: "/admin/main",
        component: () => import("@/components/views/Main.vue"),
        children: [
            {
                name: "customer",
                path: "/admin/main/customer",
                component: () => import("@/components/views/Customer.vue")
            },
            {
                name: "adminVenue",
                path: "/admin/main/venue",
                component: () => import("@/components/views/Venue.vue")
            },
            {
                name: "adminReservation",
                path: "/admin/main/reservation",
                component: () => import("@/components/views/Reservation.vue")
            },
            {
                name: "history",
                path: "/admin/main/history",
                component: () => import("@/components/views/History.vue")
            },
        ]
    },
    {
        name: "index",
        path: "/",
        redirect: "/admin/main"
    }
];

//定义路由转发器
const router = createRouter({
    routes,
    history: createWebHistory()
});

//配置路由守卫
router.beforeEach((to, from, next) => {
    let jwt = getJwt();
    if(!jwt) {
        if (to.name !== "login") {
            next("/login");
        } else {
            next();
        }
    }
    //登录成功
    const role = decodeJwt().role;
    if (to.name === "login") {
        if (role === "admin") {
            next("/admin/main");
        } else {
            next("/normal/main");
        }
    } else {
        //控制访问权限
        if (to.path.startsWith("/admin") && role !== "admin") {
            //普通用户访问管理员页面 跳转回普通用户主页
            next("/normal/main");
        } else if (to.path.startsWith("/normal") && role !== "normal") {
            //管理员访问普通用户页面 跳转回管理员主页
            next("/admin/main");
        } else {
            //允许访问
            next();
        }
    }

})

export default router;
